package com.coocaa.x.service.litecontent.providers.apps.controller;

import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.litecontent.providers.apps.data.AppLastStartTimesTableData;

import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.List;


public class AppLastStartTimesDataController {
    private static AppLastStartTimesDataController instance = null;
    private static final int MAXCOUNT = 50;

    public static AppLastStartTimesDataController getInstance() {
        if (instance == null) {
            instance = new AppLastStartTimesDataController();
        }
        return instance;
    }

    private AppLastStartTimesDataController() {

    }

    public void insert(String pkg) {
        LogUtils.d("base", "AppLastStartTimesDataController  insert");
        List<AppLastStartTimesTableData> list = DataSupport
                .findAll(AppLastStartTimesTableData.class);
        if (list != null && list.size() >= MAXCOUNT) {
            LogUtils.d("base", "AppLastStartTimesDataController  insert size:" + list.size());
            AppLastStartTimesTableData data = DataSupport.findFirst(AppLastStartTimesTableData.class);
            int id = data.getId();
            DataSupport.delete(AppLastStartTimesTableData.class, id);
        }
        AppLastStartTimesTableData data = new AppLastStartTimesTableData();
        data.setPkgName(pkg);
        data.save();
    }

    public int getRecentlyUsedTimes(String pkg) {
        List<AppLastStartTimesTableData> list = DataSupport.where("pkgName = ?", pkg).find(
                AppLastStartTimesTableData.class);
        if (list != null && list.size() > 0) {
            int count = list.size();
            LogUtils.d("base", "AppLastStartTimesDataController  insert  count: " + count);
            return count;
        }
        LogUtils.d("base", "AppLastStartTimesDataController  insert  count: 0");
        return 0;
    }

    public HashMap<String, Integer> getLastAppStartTimesMap() {
        List<AppLastStartTimesTableData> list = DataSupport
                .findAll(AppLastStartTimesTableData.class);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for (AppLastStartTimesTableData data : list) {
            String pkg = data.getPkgName();
            if (map.containsKey(pkg)) {
                int time = map.get(pkg) + 1;
                map.put(pkg, time);
            } else {
                map.put(pkg, 1);
            }
        }
        LogUtils.d("app", "getLastAppStartTimesMap  size:" + map.size());
        return map;
    }
}
